package com.woniuxy.microsystemsarserver.controller;

import com.github.pagehelper.PageInfo;
import com.slsupermarket.common.res.ResponseMsg;
import com.woniuxy.microsystemsarserver.bean.InvoiceBean;
import com.woniuxy.microsystemsarserver.bean.PageRequestBean;
import com.woniuxy.microsystemsarserver.bean.StoreBean;
import com.woniuxy.microsystemsarserver.bean.TerminalBean;
import com.woniuxy.microsystemsarserver.service.ITerminalService;
import com.woniuxy.microsystemsarserver.util.DateUtil;
import com.woniuxy.microsystemsarserver.util.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 终端管理
 * @author 杨灿
 */
@RestController
@RequestMapping("/terminal")
public class TerminalController {
    @Resource
    private ITerminalService terminalService;
    /**
     * 分页查询终端信息
     * @param terminalBean
     * @param currentPage
     * @param userId
     * @return
     */
    @RequestMapping("/allByPage")
    public ResponseMsg findByPage(TerminalBean terminalBean, Integer currentPage, Long userId){
        PageRequestBean pageRequestBean = new PageRequestBean();
        pageRequestBean.setPageNum(currentPage);
        pageRequestBean.setLimit(5);
        PageInfo<TerminalBean> byPage = terminalService.findByPage(terminalBean, pageRequestBean, userId);
        return new ResponseMsg().builder().code(200).data(byPage).msg("查询成功").build();
    }

    /**
     * 查询所有终端
     * @param
     * @param
     * @param userId
     * @return
     */
    @RequestMapping("/all")
    public ResponseMsg findAll(Long userId){
        List<TerminalBean> all = terminalService.findAll(userId);
        return new ResponseMsg().builder().code(200).data(all).msg("查询成功").build();
    }

    /**
     * 根据id查询终端信息
     * @param terminalId
     * @return
     */
    @RequestMapping("/findById")
    public ResponseMsg findById(Long terminalId){
        TerminalBean terminalBean = terminalService.findById(terminalId);
        return new ResponseMsg().builder().code(200).data(terminalBean).msg("查询成功").build();
    }

    /**
     * 新增终端
     * @param terminalBean
     * @return
     */
    @RequestMapping("/add")
    public ResponseMsg saveTerminal(TerminalBean terminalBean,Long storeId){

        StoreBean storeBean = new StoreBean();
        storeBean.setId(storeId);
        terminalBean.setStoreBean(storeBean);
        System.out.println(terminalBean);
        int row = terminalService.saveTerminal(terminalBean);
        if (row>0){
            return new ResponseMsg().builder().code(200).msg("添加成功").build();
        }else {
            return new ResponseMsg().builder().code(201).msg("添加失败").build();
        }

    }
    /**
     * 修改终端
     * @param terminalBean
     * @return
     */
    @RequestMapping("/update")
    public ResponseMsg updateTerminal(TerminalBean terminalBean){

        int row = terminalService.updateTerminal(terminalBean);
        if (row>0){
            return new ResponseMsg().builder().code(200).msg("修改成功").build();
        }else {
            return new ResponseMsg().builder().code(201).msg("修改失败").build();
        }

    }

    /**
     *导出当前用户的终端记录信息为excel
     * @return
     */
    @RequestMapping("/exportAll")
    public ResponseMsg exportAudit(long userId, HttpServletRequest request, HttpServletResponse response) throws Exception {

        //获取数据
        List<TerminalBean> list = terminalService.findAll(userId);
        // System.out.println(list);
        //excel标题
        String[] title = {"序号","门店名称","终端编码","唯一码","设备名称","登记日期","状态"};

        //excel文件名
        String fileName = "终端信息表"+System.currentTimeMillis()+".xls";

        //sheet名
        String sheetName = "终端信息表";
        String[][] content = new String[list.size()+1][title.length];
        for (int i = 0; i < list.size(); i++) {
            TerminalBean obj = list.get(i);
            content[i][0] = i+1 +"";
            content[i][1] = obj.getStoreBean().getStoreName();
            content[i][2] = obj.getTerminalNum();
            content[i][3] = obj.getUniqueNum();
            content[i][4] = obj.getTerminalName();
            content[i][5] = DateUtil.DateToStr(obj.getRegisterTime(),"yyyy-MM-dd hh:mm:ss");
            if (obj.getTerminalStatus()==0){
                content[i][6] = "正常";
            }else if (obj.getTerminalStatus()==1){
                content[i][6] = "关闭";
            }

        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
            this.setResponseHeader(response,fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送响应流方法
     * @param response
     * @param fileName
     */
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/x-msdownload;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
